package com.android.powerbankpad;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Instrumentation;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.LocaleList;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;
import androidx.viewpager.widget.ViewPager;

import com.android.powerbankpad.adapter.AdAdapter;
import com.android.powerbankpad.api.ApiUrl;
import com.android.powerbankpad.audio.BeepManager;
import com.android.powerbankpad.bean.AdBean;
import com.android.powerbankpad.bean.CheckVersionBean;
import com.android.powerbankpad.bean.ChildBean;
import com.android.powerbankpad.bean.DeviceInfoBean;
import com.android.powerbankpad.bean.GetAudioBean;
import com.android.powerbankpad.bean.LoginBean;
import com.android.powerbankpad.bean.OrderBean;
import com.android.powerbankpad.bean.RentBean;
import com.android.powerbankpad.bean.SocketBean;
import com.android.powerbankpad.config.Constants;
import com.android.powerbankpad.dialog.AlarmDialog;
import com.android.powerbankpad.dialog.PosRentResultDialog;
import com.android.powerbankpad.dialog.RentResultDialog;
import com.android.powerbankpad.download.DownObservable;
import com.android.powerbankpad.download.FileDownloader;
import com.android.powerbankpad.network.CommonalityModel;
import com.android.powerbankpad.network.NetWorkListener;
import com.android.powerbankpad.network.okHttpModel;
import com.android.powerbankpad.network.retrofit.ApiUtils;
import com.android.powerbankpad.posutils.PosSerialPort;
import com.android.powerbankpad.receiver.NetBroadcastReceiver;
import com.android.powerbankpad.socket.PowerWebSocketClient;
import com.android.powerbankpad.ui.MyFragment;
import com.android.powerbankpad.utils.TimerPlayUtils;
import com.android.powerbankpad.view.NoScrollViewPager;
import com.huawei.hms.hmsscankit.ScanUtil;
import com.huawei.hms.hmsscankit.WriterException;
import com.huawei.hms.ml.scan.HmsBuildBitmapOption;
import com.meiai.manager.MyManager;
import com.ws.universal.tools.OrrorLog;
import com.ws.universal.tools.base.BaseActivity;
import com.ws.universal.tools.carsh.FileWriteUtils;
import com.ws.universal.tools.countdown.CommitTimer;
import com.ws.universal.tools.countdown.CountDown;
import com.ws.universal.tools.countdown.TimeCount;
import com.ws.universal.tools.eventbus.BaseBusData;
import com.ws.universal.tools.eventbus.EventBusUtil;
import com.ws.universal.tools.network.JSONFormat;
import com.ws.universal.tools.utils.AppUtils;
import com.ws.universal.tools.utils.CacheUtils;
import com.ws.universal.tools.utils.DeviceUtils;
import com.ws.universal.tools.utils.DisplayUtils;
import com.ws.universal.tools.utils.EncryptUtils;
import com.ws.universal.tools.utils.FileIOUtils;
import com.ws.universal.tools.utils.FileUtils;
import com.ws.universal.tools.utils.GsonUtils;
import com.ws.universal.tools.utils.LocationUtils;
import com.ws.universal.tools.utils.LogcatUtils;
import com.ws.universal.tools.utils.NetWorkUtils;
import com.ws.universal.tools.utils.ScreenUtils;
import com.ws.universal.tools.utils.ShellUtils;
import com.ws.universal.tools.utils.StringUtils;
import com.ws.universal.tools.utils.ThreadUtils;
import com.ws.universal.tools.utils.TimeDateUtils;
import com.ws.universal.tools.utils.ToastUtils;
import com.ws.universal.tools.utils.cache.CacheDoubleStaticUtils;
import com.ws.universal.tools.utils.cache.FilePathUtils;
import com.ws.universal.tools.utils.glide.GlideUtils;
import com.ws.universal.tools.wsui.help.LangHelper;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Timer;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.observers.DefaultObserver;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.autosize.internal.CustomAdapt;
import okhttp3.ResponseBody;
import xyz.doikki.videoplayer.player.BaseVideoView;
import xyz.doikki.videoplayer.player.VideoView;

import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;

public class MainActivity extends BaseActivity implements CustomAdapt, NetBroadcastReceiver.netEventHandler, NetWorkListener {
    private WebSocketClient mSocketClient;
    //private boolean isQUAD_COREA133c3;//是否为QUAD-COREA133c3设备
    private BeepManager beepManager;

    private int layoutId;
    private RelativeLayout rlAllLayout;
    private RelativeLayout llBottom;
    private ImageView mIvQrCode;
    private ImageView mIvBottom;
    private ImageView imgNetworkError;
    private TextView tvVersion;
    private int screenOrientation = 1;//屏幕方向 1竖屏 2横屏
    private NoScrollViewPager viewPage;
    private AdAdapter adAdapter;
    //private MultipleTypesAdapter bannerAdapter;
    //private Banner banner;
    private List<ChildBean> listData;
    private List<MyFragment> fragments;
    private NetBroadcastReceiver mNetBroadcastReceiver;

    private BaseBusData beautyDate;
    private Intent intent;
    private ImageView imgTop;
    private ImageView imgBot;
    private Handler handler;

    private CheckVersionBean versionBean;

    //轮询
    private TimeCount timeCount;
    private LinearLayout llPosView;
    private LinearLayout llStepTwo;
    private TextView tvStepOne;
    private TextView tvStepTwo;
    private MyFragment myFragment;
    private VideoView videoView;
    private ProgressBar experienceProgressBar;
    private TextView tvProgressBar;


    private String mType;
    private DeviceInfoBean deviceInfoBean;
    private PosRentResultDialog posRentResultDialog;

    private String topDefultAdData = "";
    private boolean isGetserial_number = false; //是否获取到了设备号
    private RentResultDialog mRentResultBuilder;
    private AlarmDialog errorPopup;


    protected DownObservable mApiService;
    private int result;//租借 归还 结果 1成功 0失败

    private int reLoadDate; //重新加载那个接口

    private RentBean rentBean;


    /*  ******************* 百富Pos机 ********************** */
    private PosSerialPort posSerialPort;
    private MyManager manager;

    private String downloadPath;
    private CompositeDisposable compositeDisposable = new CompositeDisposable();

    @Override
    protected void initCreate(Bundle savedInstanceState) {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        EventBusUtil.resgisterEventBus(this);
        mApiService = ApiUtils.getInstance().getApiService();
        intent = getIntent();
        //根据屏幕分辨率 设置横竖屏
        if (ScreenUtils.getScreenWidth() < ScreenUtils.getScreenHeight()) {
            ScreenUtils.setPortrait(this);
            layoutId = R.layout.activity_main_portrait;
            screenOrientation = 1;
        } else {
            ScreenUtils.setLandscape(this);
            layoutId = R.layout.activity_main_landscape;
            screenOrientation = 2;
        }
        manager = MyManager.getInstance(this);
        manager.bindAIDLService(this);
        manager.setConnectClickInterface(new MyManager.ServiceConnectedInterface() {
            @Override
            public void onConnect() {
                //回调成功,可以正常调用接口了
                //例如：manager. getApiVersion();
            }
        });

        //CacheUtils.setString(Constants.serial_number, "GT042240112079");
        setContentView(layoutId);


    }

    private ShellUtils.CommandResult resultBA30;

    @SuppressLint({"MissingPermission", "WrongConstant"})
    @Override
    protected void initView() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                resultBA30 = ShellUtils.execCmd("getprop ro.build.display.id");
            }
        }).start();


        rlAllLayout = findViewById(R.id.rlAllLayout);
        llBottom = findViewById(R.id.llBottom);
        tvVersion = findViewById(R.id.tvVersion);
        mIvQrCode = findViewById(R.id.mIvQrCode);
        mIvBottom = findViewById(R.id.mIvBottom);
        imgNetworkError = findViewById(R.id.imgNetworkError);
        viewPage = findViewById(R.id.viewPage);
        experienceProgressBar = findViewById(R.id.experienceProgressBar);
        tvProgressBar = findViewById(R.id.tvProgressBar);
        //banner = findViewById(R.id.banner);


        llPosView = findViewById(R.id.llPosView);
        llStepTwo = findViewById(R.id.llStepTwo);
        tvStepOne = findViewById(R.id.tvStepOne);
        tvStepTwo = findViewById(R.id.tvStepTwo);


        beepManager = new BeepManager(this);


        if (screenOrientation == 1) {
            imgTop = findViewById(R.id.imgTop);
            imgBot = findViewById(R.id.imgBot);
        }

        MainTools.getInstance().checkPermissions();
        NetBroadcastReceiver.mListeners.add(this);
        mNetBroadcastReceiver = new NetBroadcastReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(NetBroadcastReceiver.NET_CHANGE_ACTION);
        registerReceiver(mNetBroadcastReceiver, filter);
        handler = new Handler();

        TimerPlayUtils.getInstance().init();
        ShellUtils.get_root();

        posSerialPort = new PosSerialPort();
        posSerialPort.setActivity(this);
        posSerialPort.initPermission();

        MainTools.getInstance().shellGetMacAddress();


        mIvBottom.setOnClickListener(view -> {


        });
        test();
        mIvQrCode.setOnClickListener(view -> {
            //FileUtils.delete("/storage/emulated/0/update.zip");

            startLocationUpdates();
        });


        posSerialPort.setPosListener(new PosSerialPort.PosListener() {
            @Override
            public void initFail() {
                ToastUtils.showShort("pos initialization fail ", 10000);
                stopProgressDialog();
                showProgressDialog(false, "pos initialization ing...");
                Observable.timer(30, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(Long aLong) {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                        posSerialPort.initSetConfig(posSerialPort.isSerialPort);
                    }
                });
            }

            @Override
            public void readCard() {
                showProgressDialog(false);
                llPosViewIsShow(View.VISIBLE);
            }

            @Override
            public void deviceScanSucceed(String text) {
                tvStepOne.setText(text);
            }

            @Override
            public void paySuccess() {
                stopProgressDialog();
                llPosViewIsShow(View.GONE);
            }

            @Override
            public void freezeFail() {
                getImageRent(0);
                stopProgressDialog();
                llPosViewIsShow(View.GONE);
            }


        });

        viewPage.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                LogcatUtils.e(" videoPlayer position  " + position);
                initGetmFragmentListChild(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });


    }

    @SuppressLint("MissingPermission")
    private void startLocationUpdates() {
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        List<String> providers = locationManager.getAllProviders();
        if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
            // 网络定位提供者存在
            LogcatUtils.d("LocationUtils  Network provider exists.");
        } else {
            // 网络定位提供者不存在
            LogcatUtils.d("LocationUtils  Network provider does not exist.");
        }

        // locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
    }

    private LocationManager locationManager;
    private LocationListener locationListener;

    private void test() {
        LogcatUtils.e("LocationUtils 执行获取定位 ");
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(@NonNull Location location) {
                double latitude = location.getLatitude();
                double longitude = location.getLongitude();
                LogcatUtils.e("LocationUtils latitude " + latitude);
                LogcatUtils.e("LocationUtils longitude " + longitude);
                // 在这里使用获取的位置信息
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
                LogcatUtils.e("LocationUtils onStatusChanged " + provider + " status " + status);
            }

            @Override
            public void onProviderEnabled(@NonNull String provider) {
                LogcatUtils.e("LocationUtils onProviderEnabled " + provider);
            }

            @Override
            public void onProviderDisabled(@NonNull String provider) {
                LogcatUtils.e("LocationUtils onProviderDisabled " + provider);
            }
        };
    }


    private void loginAccount() {

        LogcatUtils.e(" loginAccount 执行登录");
        String serviceVersionName = null;
        if (AppUtils.isAppInstalled(Constants.SERVICE_PACKAGE_NAME)) {
            serviceVersionName = AppUtils.getAppVersionName(Constants.SERVICE_PACKAGE_NAME);
        }

        String service2VersionName = null;
        if (AppUtils.isAppInstalled(Constants.SERVICE2_PACKAGE_NAME)) {
            service2VersionName = AppUtils.getAppVersionName(Constants.SERVICE2_PACKAGE_NAME);
        }
        //LogcatUtils.e(TAG + " serviceVersionName " + serviceVersionName + " serviceVersionName2 " + service2VersionName);
        if (StringUtils.isEmpty(serviceVersionName) && StringUtils.isEmpty(service2VersionName)) {
            mType = "mac";
            showVersion();
            getDeviceInfo(true);
        } else {
            mType = "sn";
            sendGetSerialNumberBroadcast();
        }
    }


    private void getDeviceInfo(boolean isMan) {
        LogcatUtils.e(" getDeviceInfo 登录 ");
        Map<String, String> params = new HashMap<>();

        if (isMan) {
            params.put("login_type", "mac");
            params.put("macAddress", CacheUtils.getString(Constants.mac_address));
        } else {
            params.put("login_type", "sn");
            params.put("sn", CacheUtils.getString(Constants.serial_number));

        }
        //把设备号写入到系统目录下zdhx/sn.log
        FileWriteUtils.writeSn(CacheUtils.getString(Constants.serial_number));
       /* params.put("login_type", "sn");
        params.put("sn", CacheUtils.getString(Constants.serial_number));*/

        params.put("md5", CacheUtils.getString(Constants.serial_number));
        params.put("stamp", StringUtils.getString(TimeDateUtils.getTimeStampSecond()));
        params.put("registrationID", CacheUtils.getString(Constants.registrationID));//友盟推送id
        params.put("version", StringUtils.getString(AppUtils.getAppVersionCode()));
        okHttpModel.post(ApiUrl.get_Wss_Address, params, ApiUrl.get_Wss_Address_Id, this);

    }


    private void dealWithDeviceInfo(String jsonData) {
        CacheDoubleStaticUtils.put(Constants.deviceData, jsonData);//二级缓存
        LogcatUtils.e(" jsonData " + JSONFormat.format(jsonData));
        deviceInfoBean = GsonUtils.parseJObject(jsonData, DeviceInfoBean.class);
        if (deviceInfoBean != null) {
            LogcatUtils.e(" deviceInfoBean " + deviceInfoBean.toString());

            CacheUtils.setString(Constants.base_url, deviceInfoBean.getHost());
            CacheUtils.setString(Constants.serial_number, deviceInfoBean.getSn());
            CacheUtils.setString(Constants.socket_host, deviceInfoBean.getWss());
            CacheUtils.setString(Constants.ocode, deviceInfoBean.getOcode());


            LogcatUtils.e(" deleteSingleFile 当前 " + deviceInfoBean.getOcode() + " 上一个 " + CacheUtils.getString(Constants.audio_path));
            if (deviceInfoBean.getOcode().equals("chargeeight")) {
                File rootDirectory = new File(FilePathUtils.getInstance().getCacheFiles().getPath() + "/" + deviceInfoBean.getOcode());
                FilePathUtils.getInstance().deleteFolder(rootDirectory);
                CacheUtils.setString(Constants.audio_path, deviceInfoBean.getOcode());
            } else {
                if (!CacheUtils.getString(Constants.audio_path).equals(deviceInfoBean.getOcode())) {
                    File rootDirectory = new File(FilePathUtils.getInstance().getCacheFiles().getPath() + "/" + CacheUtils.getString(Constants.audio_path));
                    FilePathUtils.getInstance().deleteFolder(rootDirectory);
                    CacheUtils.setString(Constants.audio_path, deviceInfoBean.getOcode());
                }
            }
            getAdList();
            whileDownAudio();
            Observable.timer(5, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Long>() {
                @Override
                public void onSubscribe(Disposable d) {
                }

                @Override
                public void onNext(Long aLong) {
                }

                @Override
                public void onError(Throwable e) {
                }

                @Override
                public void onComplete() {
                    checkVersionApi();

                    initSocket();

                }
            });

            sendLcsCommand(deviceInfoBean.getOcode(), deviceInfoBean.getSn());
        }
    }


    //发送LCS检测升级指令
    public void sendLcsCommand(String ocode, String sn) {
        LogcatUtils.e(" sendConnectState2Serial 发送lcs升级检测命令 ");
        Intent intent = new Intent(Constants.SEND_BROADCAST_ACTION_LCS);
        intent.putExtra("ocode", ocode);
        intent.putExtra("sn", sn);
        intent.setComponent(new ComponentName("com.lechang.service2", "com.lechang.service2.ThirdAppReceiver"));
        MainActivity.this.sendBroadcast(intent);
    }

    private Timer timer;

    private void whileDownAudio() {

        if (timer == null) {
            timer = new Timer();
        }

        timer.scheduleAtFixedRate(new CommitTimer() {
            @Override
            public void run() {
                getDownAudio();
            }
        }, 3000, 30000);
    }

    private void timerFinish() {
        if (timer != null) {
            timer.cancel();
            timer.purge();
            timer = null;
        }
    }


    private void getAdList() {
        String baseUrl = CacheUtils.getString(Constants.base_url) + "/cloud/screen/plan";
        Map<String, String> params = new HashMap<>();
        params.put("sn", CacheUtils.getString(Constants.serial_number));
        params.put("ocode", CacheUtils.getString(Constants.ocode));
        params.put("stamp", StringUtils.getString(TimeDateUtils.getTimeStampSecond()));

        okHttpModel.post(baseUrl, params, ApiUrl.get_Advertising_Id, this);


    }


    private void dealWithAd(String jsonData) {
        CacheDoubleStaticUtils.put(Constants.adData, jsonData);//二级缓存
        AdBean adBean = GsonUtils.parseJObject(jsonData, AdBean.class);
        if (adBean != null) {
            /*开始设置横竖屏对应的区块划分 并且设置高度*/
            LogcatUtils.e("设置屏幕 " + (screenOrientation == 1 ? "竖屏" : "横屏"));
            if (screenOrientation == 1) { //竖屏
                GlideUtils.CreateImageRound(adBean.bottom.img, mIvBottom);
                if (adBean.top != null && !StringUtils.isEmpty(adBean.top.img) && adBean.top.height > 0) {
                    setViewHeight(imgTop, adBean.top.height);
                    GlideUtils.CreateImageRound(adBean.top.img, imgTop);
                } else {
                    setViewHeight(imgTop, 0);
                }
                if (adBean.middle != null && !StringUtils.isEmpty(adBean.middle.img) && adBean.middle.height > 0) {
                    setViewHeight(imgBot, adBean.middle.height);
                    GlideUtils.CreateImageRound(adBean.middle.img, imgBot);
                } else {
                    setViewHeight(imgBot, 0);
                }

                if (adBean.bottom != null && adBean.bottom.height > 0) {
                    setViewHeight(llBottom, adBean.bottom.height);
                } else {
                    setViewHeight(llBottom, 0);
                }
            } else { //横屏
                GlideUtils.CreateImageRound(adBean.left, mIvBottom);
                //GlideUtils.CreateImageRound("https://charge8-dev.w-dian.cn/uploads/202308/16934778591470.png", mIvBottom);
            }
            mIvQrCode.setImageBitmap(CacheDoubleStaticUtils.getBitmap(Constants.qrcode));
            topDefultAdData = "";
            MainTools.getInstance().setScreenOrientation(screenOrientation);
            if (null != adBean && adBean.list.size() > 0) {
                //开启轮询
                MainTools.getInstance().pollingLoadAd(adBean);
            } else {
                //都不符合, 显示默认图片
                MainTools.getInstance().playDefaultImage(adBean);
            }

        }
    }


    /**
     * 获取音频
     */
    private void getDownAudio() {
        String url = CacheUtils.getString(Constants.base_url) + "/cloud/screen/audio";


        mApiService.getAudio(url, CacheUtils.getString(Constants.serial_number))

                .subscribeOn(Schedulers.io()).observeOn(Schedulers.io()).subscribe(new DefaultObserver<GetAudioBean>() {
                    @Override
                    public void onNext(GetAudioBean download) {


                        File d = new File(FilePathUtils.getInstance().getCacheFiles(), CacheUtils.getString(Constants.audio_path));
                        if (!d.exists()) {
                            d.mkdirs();
                        }

                        if (!getPathAudio(d, Constants.boot_strap)) {

                            downAudio(d, download.getBoot_strap(), Constants.boot_strap);
                        } else {
                            if (!pathAudioSize(d, Constants.boot_strap)) {
                                deleteAudio(d, Constants.boot_strap);
                            }
                        }

                        if (!getPathAudio(d, Constants.networking_success)) {
                            downAudio(d, download.getNetworking_success(), Constants.networking_success);

                        } else {
                            if (!pathAudioSize(d, Constants.networking_success)) {
                                deleteAudio(d, Constants.networking_success);
                            }
                        }

                        if (!getPathAudio(d, Constants.networking_fail)) {
                            downAudio(d, download.getNetworking_fail(), Constants.networking_fail);

                        } else {
                            if (!pathAudioSize(d, Constants.networking_fail)) {
                                deleteAudio(d, Constants.networking_fail);
                            }
                        }

                        if (!getPathAudio(d, Constants.rent_success)) {
                            downAudio(d, download.getRent_success(), Constants.rent_success);

                        } else {
                            if (!pathAudioSize(d, Constants.rent_success)) {
                                deleteAudio(d, Constants.rent_success);
                            }
                        }

                        if (!getPathAudio(d, Constants.rent_fail)) {
                            downAudio(d, download.getRent_fail(), Constants.rent_fail);

                        } else {
                            if (!pathAudioSize(d, Constants.rent_fail)) {
                                deleteAudio(d, Constants.rent_fail);
                            }
                        }

                        if (!getPathAudio(d, Constants.return_success)) {
                            downAudio(d, download.getReturn_success(), Constants.return_success);
                        } else {
                            if (!pathAudioSize(d, Constants.return_success)) {
                                deleteAudio(d, Constants.return_success);
                            }
                        }

                        if (!getPathAudio(d, Constants.return_fail)) {
                            downAudio(d, download.getReturn_fail(), Constants.return_fail);

                        } else {
                            if (!pathAudioSize(d, Constants.return_fail)) {
                                deleteAudio(d, Constants.return_fail);
                            }
                        }


                        if (getPathAudio(d, Constants.networking_success) && pathAudioSize(d, Constants.networking_success) && getPathAudio(d, Constants.networking_fail) && pathAudioSize(d, Constants.networking_fail) && getPathAudio(d, Constants.return_success) && pathAudioSize(d, Constants.return_success) && getPathAudio(d, Constants.return_fail) && pathAudioSize(d, Constants.return_fail) && getPathAudio(d, Constants.rent_success) && pathAudioSize(d, Constants.rent_success) && getPathAudio(d, Constants.rent_fail) && pathAudioSize(d, Constants.rent_fail)) {
                            BaseBusData beautyDate = new BaseBusData(Constants.stop_down_audio);
                            EventBusUtil.postEvent(beautyDate);
                        }


                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    /**
     * 版本更新
     */
    private void checkVersionApi() {
        Map<String, String> params = new HashMap<>();
        params.put("sn", CacheUtils.getString(Constants.serial_number));
        params.put("ocode", CacheUtils.getString(Constants.ocode));
        params.put("version", StringUtils.getString(AppUtils.getAppVersionCode()));
        params.put("system_name", DeviceUtils.getSDKVersionName());
        params.put("system_code", manager.getFirmwareVersion());
        params.put("mainboard", manager.getDeviceModle());
        /*if (getLocation() != null) {
            params.put("latitude", getLocation().getLatitude() + "");
            params.put("longitude", getLocation().getLongitude() + "");
        } else {
            LogcatUtils.e("LocationUtils  为空 ");
        }*/
        okHttpModel.post(ApiUrl.check_version, params, ApiUrl.check_version_Id, this);
    }


    /**
     * 连接Socket
     */
    private void initSocket() {

        String wssAddress = CacheUtils.getString(Constants.socket_host);

        LogcatUtils.d("MySocketConnect   initSocket: ------wssAddress 为 : " + wssAddress + " time " + TimeDateUtils.getCurrentDate("yyyy-MM-dd hh:mm:ss", TimeDateUtils.getTimeStamp()));
        if (StringUtils.isEmpty(wssAddress)) {
            LogcatUtils.d("MySocketConnect  MainActivity initSocket: ------wssAddress为空: ");
            return;
        }
        if (null != mSocketClient && mSocketClient.isOpen()) {
            LogcatUtils.d("MySocketConnect  MainActivity initSocket: -----socket 已连接: ");
            return;
        }
        try {
            mSocketClient = new PowerWebSocketClient(new URI(CacheUtils.getString(Constants.socket_host))) {
                @Override
                public void onOpen(ServerHandshake handshakedata) {
                    LogcatUtils.d("MySocketConnect  onOpen: ------连接成功!!!");

                    //登录
                    SocketBean bean = new SocketBean("login");
                    LogcatUtils.e(" MySocket 执行屏幕登录 " + GsonUtils.toJsonObjectSerializeNulls(bean) + " time " + TimeDateUtils.getCurrentDate("yyyy-MM-dd hh:mm:ss", TimeDateUtils.getTimeStamp()));
                    sendSocketMsg(GsonUtils.toJsonObjectSerializeNulls(bean));
                    sendHeartbeatTimer();

                }

                @Override
                public void onMessage(String message) {
                    //LogcatUtils.e(TAG + "   MySocket 收到消息:" + message);
                    Observable.just("123").subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).doOnNext(new Consumer<String>() {
                        @Override
                        public void accept(String s) throws Exception {
                            JSONObject object = new JSONObject(message.replace(Constants.sockect_head, "").replace(Constants.sockect_tail, ""));
                            parseSocketMessage(object);
                        }
                    }).subscribe();

                }

                @Override
                public void onClose(int code, String reason, boolean remote) {

                    LogcatUtils.e("onClose MySocketConnect 连接关闭  执行重新链接 " + reason + "  code:" + code);
                    if (mSocketClient.isClosed()) {
                        OrrorLog.updateLog("onClose MySocketConnect 连接关闭  执行重新链接 " + reason + "  code:" + code);
                        reLoadDate(4);
                    }
                }

                @Override
                public void onError(Exception ex) {
                    OrrorLog.updateLog("onError MySocketConnect 连接异常  执行重新链接 " + ex.toString());
                    LogcatUtils.e("onError MySocketConnect 连接异常  执行重新链接 " + ex.toString());
                    reLoadDate(4);

                }
            };


            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new TrustManager[]{new X509TrustManager() {

                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType) {

                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType) {

                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }
            }}, new SecureRandom());
            SSLSocketFactory factory = sslContext.getSocketFactory();
            mSocketClient.setSocketFactory(factory);
            mSocketClient.connect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private ThreadUtils.Task reLoadDateThread = new ThreadUtils.Task() {
        @Override
        public Object doInBackground() throws Throwable {


            switch (reLoadDate) {
                case 0:
                    loginAccount();
                    break;
                case 1:
                    if (!TextUtils.isEmpty(CacheUtils.getString(Constants.base_url)) && (CacheUtils.getString(Constants.base_url).indexOf("https:") > 0 || CacheUtils.getString(Constants.base_url).indexOf("http:") > 0)) {
                        getAdList();
                    }
                    break;
                case 2:
                    if (!TextUtils.isEmpty(CacheUtils.getString(Constants.base_url)) && (CacheUtils.getString(Constants.base_url).indexOf("https:") > 0 || CacheUtils.getString(Constants.base_url).indexOf("http:") > 0)) {
                        getDownAudio();
                    }

                    break;
                case 3:
                    checkVersionApi();
                    break;
                case 4:
                    mSocketClient.reconnect();
                    break;

            }
            return null;
        }

        @Override
        public void onSuccess(Object result) {

        }

        @Override
        public void onCancel() {

        }

        @Override
        public void onFail(Throwable t) {

        }
    };

    private void reLoadDate(int action) {
        reLoadDate = action;
        ThreadUtils.executeBySingleWithDelay(reLoadDateThread, 10, TimeUnit.SECONDS);
    }



    /**
     * 发送心跳包
     */
    private void sendHeartbeatTimer() {
        //ThreadUtils.cancel(heartThread);
        handler.removeCallbacks(heartbeat);
        handler.postDelayed(heartbeat,5000);
    }
    private Runnable heartbeat=new Runnable() {
        @Override
        public void run() {
            String versionName = AppUtils.getAppVersionName();
            String s = "{\"cmd\":\"heart\",\"v\":\"" + versionName + "\"}";
            LogcatUtils.e("MySocketConnect   发送Socket心跳消息 :" + s);
            sendSocketMsg(s);
            // 再次延迟5秒执行
            handler.postDelayed(this, 5000);
        }
    };



    /**
     * 发送消息
     *
     * @param msg 消息 不含包头包尾
     */
    public void sendSocketMsg(String msg) {

        //msg = "$##" + msg + "##$";
        msg = StringUtils.getString(Constants.sockect_head, msg, Constants.sockect_tail);
        //LogcatUtils.d(" sendSocketMsg 发送Socket心跳消息: " + msg);
        //LogcatUtils.e(" MySocket  sendSocketMsg " + msg);
        if (mSocketClient != null) {

            mSocketClient.send(msg);
        }

    }


    /**
     * 解析 收到的socket 消息
     *
     * @param message
     */
    private void parseSocketMessage(JSONObject message) {


        switch (message.optString("cmd")) {
            case Constants.cmd_hard:
                LogcatUtils.e("MySocketConnect parseSocketMessage 收到socket消息 " + message + " time " + TimeDateUtils.getCurrentDate("yyyy-MM-dd hh:mm:ss", TimeDateUtils.getTimeStamp()));
                break;
            case Constants.cmd_login:
                //登陆消息
                LoginBean loginBean = GsonUtils.fromJson(message.toString(), LoginBean.class);

                if (null != loginBean) {
                    //loginBean.getStatus()
                    if (loginBean.getStatus() == 1) {
                        LogcatUtils.e("MySocketConnect 屏幕登录成功: " + message);
                        if (!StringUtils.isEmpty(loginBean.getBackground_color())) {
                            llBottom.setBackgroundColor(Color.parseColor(loginBean.getBackground_color()));
                        }

                        if (!StringUtils.isEmpty(loginBean.getQrcode())) {
                            try {

                                HmsBuildBitmapOption options = new HmsBuildBitmapOption.Creator().setBitmapMargin(1).setBitmapColor(Color.BLACK).setBitmapBackgroundColor(Color.WHITE).create();
                                Bitmap resultImage = ScanUtil.buildBitmap(loginBean.getQrcode(), 0, DisplayUtils.dipTopx(280), DisplayUtils.dipTopx(280), options);
                                CacheDoubleStaticUtils.put(Constants.qrcode, resultImage);//二级缓存
                                LogcatUtils.d(" 加载二维码 " + message);
                                mIvQrCode.setImageBitmap(CacheDoubleStaticUtils.getBitmap(Constants.qrcode));
                            } catch (WriterException e) {
                                ToastUtils.showShort("Parameter Error!", 5000);

                                LogcatUtils.d(" Parameter Error! " + message);
                            }

                        }
                        if (!StringUtils.isEmpty(loginBean.getLang())) {
                            CacheUtils.setString(Constants.langCode, loginBean.getLang());
                            //CacheUtils.setString(Constants.langCode, "en-us");


                        }
                        //设置音量
                        setStreamMusicVolume(loginBean.getVolume());
                        //setStreamMusicVolume(10);

                        if (loginBean.getDevice_config() != null) {
                            switch (loginBean.getDevice_config().getDevice()) {
                                case 1://百富pos机
                                    if (!posSerialPort.isPosDevice) {
                                        LogcatUtils.e("  pos机 准备初始化 ");
                                        showProgressDialog(false, "pos initialization ing...");
                                        Observable.timer(30, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Long>() {
                                            @Override
                                            public void onSubscribe(Disposable d) {
                                            }

                                            @Override
                                            public void onNext(Long aLong) {
                                            }

                                            @Override
                                            public void onError(Throwable e) {
                                            }

                                            @Override
                                            public void onComplete() {
                                                LogcatUtils.e("  pos机 初始化 ");
                                                if (loginBean.getDevice_config().getDevice_type() == 1) {
                                                    posSerialPort.getUsbPermission(loginBean.getDevice_config().getAmount());
                                                } else {
                                                    posSerialPort.initPosSerialParams(loginBean.getDevice_config().getAmount());
                                                }


                                            }
                                        });
                                    }
                                    posSerialPort.isPosDevice = true;
                                    break;

                            }
                        }
                        //pos机初始化

                    } else {
                        LogcatUtils.e("onError MySocketConnect 屏幕登录失败 执行重新登录 ");
                        reLoadDate(4);
                    }


                } else {
                    LogcatUtils.d("  MySocketConnect LoginBean登录失败: " + message);
                }
                break;
            case Constants.cmd_refresh:
                //刷新广告
                LogcatUtils.e("  收到刷新广告命令 ");
                topDefultAdData = "";
                getAdList();
                break;
            case Constants.cmd_update:
                //更新app
                LogcatUtils.d("  更新app ");
                CheckVersionBean bean = GsonUtils.fromJson(message.toString(), CheckVersionBean.class);
                if (null != bean) {
                    LogcatUtils.d(" download 服务器的App VersionCode:  " + bean.getVersion());
                    downloadApk(bean);
                }
                break;

            case Constants.reload_audio:
                LogcatUtils.e("  MySocketConnect cmd_reaudio 收到 socket消息 " + message + " 重新下载音频 ");
                File rootDirectory = new File(FilePathUtils.getInstance().getCacheFiles().getPath() + "/" + CacheUtils.getString(Constants.audio_path));
                FilePathUtils.getInstance().deleteFolder(rootDirectory);
                whileDownAudio();
                break;

            case Constants.cmd_order:
                LogcatUtils.e("  MySocketConnect cmd_order 收到 socket消息 " + message);
                OrderBean orderBean = GsonUtils.fromJson(message.toString(), OrderBean.class);
                showPosRentResultDialog(orderBean);
                posSerialPort.loopCheckoutOrder = false;
                posSerialPort.checkoutOrder();
                break;


            case Constants.cmd_paymentcode:
                stopProgressDialog();
                LogcatUtils.e("  收到 paymentcode 命令 stopProgressDialog ");
                showProgressDialog(false, message.optString("msg"));
                break;

        }


    }


    private void showPosRentResultDialog(OrderBean orderBean) {
        beepManager.startAudio(Constants.return_success);
        posRentResultDialog = new PosRentResultDialog(getContext());
        posRentResultDialog.setData(orderBean);
        if (!posRentResultDialog.isShowing()) posRentResultDialog.show();
    }

    /**
     * 设置音量
     *
     * @param vol
     */
    public void setStreamMusicVolume(int vol) {
        //音量
        //音量控制
        AudioManager mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        //最大音量  
        int maxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        double i = vol / 100d;
        int volume = (int) (maxVolume * i);
        LogcatUtils.d(" 音量大小 volume::  " + volume);
        mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volume, AudioManager.FLAG_SHOW_UI);


    }

    private void sendGetSerialNumberBroadcast() {
        Intent intent = new Intent(Constants.GET_SERNUM_BROADCAST_ACTION);
        intent.setComponent(new ComponentName("com.lechang.service2", "com.lechang.service2.ThirdAppReceiver"));
        MainActivity.this.sendBroadcast(intent);
        LogcatUtils.e("   发送 获取序列号的广播  ");

    }


    public void setViewHeight(View view, int height) {
        view.setVisibility(View.VISIBLE);
        ViewGroup.LayoutParams params = view.getLayoutParams();

        params.height = height;
        view.setLayoutParams(params);
    }


    private void llPosViewIsShow(int visibility) {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {

                llPosView.setVisibility(visibility);
            }
        }, 0);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)  //3.0之后，需要加注解
    public void onEventMainThread(BaseBusData data) {
        LogcatUtils.e(" onEventMainThread  data.str " + data.str);
        switch (data.str) {
            case Constants.execute_permissions: //执行权限成功
                showProgressDialog(false, getString(com.ws.universal.tools.R.string.loading));
                loginAccount();
                break;
            case Constants.serial_number_null: //执行获取设备号
                ToastUtils.showShort(" Device code is null ");
                Observable.timer(3000L, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(Long aLong) {
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                        sendGetSerialNumberBroadcast();
                    }
                });

                break;
            case Constants.SET_SERNUM_BROADCAST_ACTION: //获取到了设备号
                if (!isGetserial_number) {
                    showVersion();
                    getDeviceInfo(false);
                    isGetserial_number = true;
                }

                break;
            case Constants.playNextAD: //切换广告

                if (listData.size() > 1) {
                    if (viewPage.getCurrentItem() == viewPage.getAdapter().getCount() - 1) {
                        viewPage.setCurrentItem(0, false);
                    } else {
                        viewPage.setCurrentItem(viewPage.getCurrentItem() + 1);
                    }

                }
                break;


            case Constants.loadAdDate: //加载广告数据
                if (listData != null) {
                    listData = null;
                }
                listData = GsonUtils.parseJArray(data.json, ChildBean.class);
                //LogcatUtils.e("                 topDefultAdData " + topDefultAdData);
                //LogcatUtils.e("data.json        topDefultAdData " + data.json);
                //LogcatUtils.e("equalsIgnoreCase topDefultAdData " + topDefultAdData.equalsIgnoreCase(data.json));
                if (!topDefultAdData.equalsIgnoreCase(data.json)) {

                    if (adAdapter != null) {
                        viewPage.removeAllViews();
                        adAdapter.removeFragment();
                    }
                    if (adAdapter == null) {
                        adAdapter = new AdAdapter(getSupportFragmentManager());
                    }
                    if (fragments != null) {
                        fragments.clear();
                    }
                    if (fragments == null) {
                        fragments = new ArrayList<>();
                    }
                   /* if (listData.size() > 3) {
                        for (int i = 0; i < listData.size(); i++) {
                            fragments.add(new MyFragment(listData.get(i)));
                        }
                    } else if (listData.size() > 1 && listData.size() <= 3) {
                        for (int k = 0; k < listData.size() * listData.size(); k++) {
                            fragments.add(new MyFragment(listData.get(k % listData.size())));
                        }
                    } else if (listData.size() > 0) {
                        fragments.add(new MyFragment(listData.get(0)));
                    }*/
                    for (int i = 0; i < listData.size(); i++) {
                        fragments.add(new MyFragment(listData.get(i)));
                    }
                    adAdapter.setDataList(fragments);
                    viewPage.setAdapter(adAdapter);
                    viewPage.setOffscreenPageLimit(listData.size());
                    initGetmFragmentListChild(0);
                    topDefultAdData = data.json;
                    LogcatUtils.e(" onEventMainThread 加载广告 完成 " + topDefultAdData);
                }

                break;

            case Constants.netWorkError:
                imgNetworkError.setVisibility(View.VISIBLE);
                break;

            case Constants.netWorkOk:
                imgNetworkError.setVisibility(View.GONE);
                Observable.timer(30000L, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(Long aLong) {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                        if (deviceInfoBean == null) {
                            BaseBusData beautyDate = new BaseBusData(Constants.execute_permissions);
                            EventBusUtil.postEvent(beautyDate);
                        }
                    }
                });
                break;
            case Constants.STRING_2:
                LogcatUtils.e(" onEventMainThread 收到网络连接ok " + data.str);

                break;

            case Constants.STRING_4://租借成功
                LogcatUtils.e("BootReceiver 租借成功 ");
                getImageRent(1);
                break;

            case Constants.STRING_5://租借失败
                getImageRent(0);
                break;

            case Constants.STRING_6://归还成功 因为有pos机  故统一由socket发送过来的命令处理
                LogcatUtils.e("BootReceiver 归还成功 ");
                getImageReturn(1);
                break;

            case Constants.STRING_7://归还失败
                getImageReturn(0);
                break;

            case Constants.STRING_8://归还失败，充电宝不属于此机柜1
                break;

            case Constants.STRING_9:
                //9网络异常，请等待联网成功后再次归还1
                break;

            /*case Constants.STRING_13://13POS机归还成功

                OrderBean orderBean = GsonUtils.fromJson(message, OrderBean.class);
                showPosRentResultDialog(orderBean);
                checkoutOrder();
                break;*/

            case Constants.reboot_app:
                LogcatUtils.e("收到 reboot_app 重启 App ");
                //@SuppressLint({"NewApi", "LocalSuppress"})
                rebootApp();

                break;

            case Constants.stop_down_audio: //停止音频数据请求
                timerFinish();
                LogcatUtils.e("onEventMainThread 停止音频数据请求");
                break;

            //获取权限
            case Constants.baifu_pos_init:
                LogcatUtils.e(" pos机 初始化成功 stopProgressDialog ");
                ToastUtils.showShort("pos initialization", 10000);
                stopProgressDialog();
                break;


        }

    }


    private void initGetmFragmentListChild(int index) {

        if (listData.size() == 1 && listData.get(0).type.equals("video")) {
            myFragment = fragments.get(0);
            if (myFragment != null) {
                videoView = myFragment.binding.videoPlayer;
                myFragment.binding.videoPlayer.setLooping(true);
                myFragment.binding.videoPlayer.release();
                myFragment.binding.videoPlayer.start();
            }

        } else if (listData.size() > 1) {
            if (videoView != null) {
                videoView.release();
                videoView.clearOnStateChangeListeners();
                videoView = null;
            }
            myFragment = fragments.get(index);
            if (myFragment != null) {
                videoView = myFragment.binding.videoPlayer;
                if (listData.get(index).type.equals("video")) {
                    myFragment.binding.videoPlayer.release();
                    myFragment.binding.videoPlayer.start();
                } else {
                    TimerPlayUtils.getInstance().playNextAD(Integer.parseInt(listData.get(index).time));
                }
            }

        }
        if (videoView != null) {
            videoView.addOnStateChangeListener(new BaseVideoView.OnStateChangeListener() {
                @Override
                public void onPlayerStateChanged(int playerState) {

                }

                @Override
                public void onPlayStateChanged(int playState) {
                    switch (playState) {


                        case VideoView.STATE_ERROR://播放错误后，为了避免一直错误，重启设备, 重启App
                            LogcatUtils.e("MyFragment state 播放错误");
                            BaseBusData error = new BaseBusData(Constants.reboot_app);
                            EventBusUtil.postEvent(error);
                            break;

                        case VideoView.STATE_PLAYBACK_COMPLETED:
                            LogcatUtils.e("videoPlayer state 播放完成");
                            BaseBusData baseBusData = new BaseBusData(Constants.playNextAD);
                            EventBusUtil.postEvent(baseBusData);
                            break;
                    }
                }
            });
        }
    }

    private void rebootApp() {
        Intent intentToStart = getPackageManager().getLaunchIntentForPackage(getPackageName());
        intentToStart.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intentToStart);
    }

    private void showVersion() {
        String s2;
        if ("mac".equals(mType)) {
            s2 = "mac";
        } else {
            s2 = AppUtils.getAppVersionName(Constants.SERVICE2_PACKAGE_NAME);
        }
        tvVersion.setText(StringUtils.getString(TextUtils.isEmpty(CacheUtils.getString(Constants.serial_number)) ? "1.0.0" : CacheUtils.getString(Constants.serial_number), "-", AppUtils.getAppVersionName(), "-", s2));
    }

    /**
     * 租借
     *
     * @param result 1成功 0失败
     */

    private void getImageRent(int result) {
        this.result = result;
        String baseUrl = CacheUtils.getString(Constants.base_url) + "/cloud/screen/rent";
        ;
        Map<String, String> params = new HashMap<>();
        params.put("sn", CacheUtils.getString(Constants.serial_number));
        okHttpModel.post(baseUrl, params, ApiUrl.screen_rent_Id, this);
    }

    private void getImageReturn(int result) {
        this.result = result;
        String baseUrl = CacheUtils.getString(Constants.base_url) + "/cloud/screen/back";
        //归还
        Map<String, String> params = new HashMap<>();
        params.put("sn", CacheUtils.getString(Constants.serial_number));
        okHttpModel.post(baseUrl, params, ApiUrl.screen_return_Id, this);
    }


    private void showResultPopup(int result, String des1, String des2, String imgUrl) {
        mRentResultBuilder = new RentResultDialog(getContext());
        mRentResultBuilder.setImage(result, des1, des2, imgUrl);
        if (!mRentResultBuilder.isShowing()) mRentResultBuilder.show();
    }


    private void showErrorPopup(String title, String content, String qrCode) {
        errorPopup = new AlarmDialog(getContext());
        errorPopup.setTitle(title);
        errorPopup.setContent(content);
        errorPopup.setLeftBtnVisibility(false);
        errorPopup.dg_divider_view.setVisibility(View.GONE);
        errorPopup.setTitleVisibility(View.VISIBLE);
        try {

            HmsBuildBitmapOption options = new HmsBuildBitmapOption.Creator().setBitmapMargin(1).setBitmapColor(Color.BLACK).setBitmapBackgroundColor(Color.WHITE).create();
            Bitmap resultImage = ScanUtil.buildBitmap(qrCode, 0, DisplayUtils.dipTopx(280), DisplayUtils.dipTopx(280), options);
            errorPopup.setDialogIcon(resultImage);
        } catch (WriterException e) {
            ToastUtils.showShort("Parameter Error!", 5000);


        }

        errorPopup.setRightBtnListener(new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                errorPopup.dismiss();
            }
        });
        if (!errorPopup.isShowing()) {
            errorPopup.show();
        }
    }


    @Override
    protected void FinishDesTroy() {
        EventBusUtil.unResgisterEventBus(this);
        MainTools.getInstance().onDesTroy();
    }

    @Override
    public boolean isBaseOnWidth() {
        return false;
    }

    @Override
    public float getSizeInDp() {
        if (ScreenUtils.getScreenWidth() < ScreenUtils.getScreenHeight()) {
            return 1730;
        } else {
            return 800;
        }

    }

    @Override
    public void onNetChange() {
        if (NetWorkUtils.getNetworkType() == NetWorkUtils.NetworkType.NETWORK_NO) {
            beautyDate = new BaseBusData(Constants.netWorkError);
            EventBusUtil.postEvent(beautyDate);
        } else {
            beautyDate = new BaseBusData(Constants.netWorkOk);
            EventBusUtil.postEvent(beautyDate);
        }
    }


    private boolean getPathAudio(File d, String pathAudio) {
        String path = d.getAbsolutePath().concat(pathAudio);
        //LogcatUtils.e(" Download " + path + " fileIsExists " + (FilePathUtils.getInstance().fileIsExists(path) ? "文件存在 走缓存 " : "不存在 则下载 "));
        return FilePathUtils.getInstance().fileIsExists(path);

    }

    private boolean pathAudioSize(File d, String pathAudio) {
        String path = d.getAbsolutePath().concat(pathAudio);
        LogcatUtils.e(" fileIsExists  " + (FilePathUtils.getInstance().getFileSize(path) > 0));
        return FilePathUtils.getInstance().getFileSize(path) > 0;

    }

    private void deleteAudio(File d, String pathAudio) {
        String path = d.getAbsolutePath().concat(pathAudio);
        FilePathUtils.getInstance().deleteFile(path);

    }

    private void downAudio(File d, String downloadPath, String fileName) {
        String path = d.getAbsolutePath().concat(fileName);
        LogcatUtils.d("Download  Audio fileName :  " + fileName);
        LogcatUtils.d("Download  Audio downloadPath :  " + downloadPath);
        LogcatUtils.d("Download  Audio path :  " + path);
        mApiService.downloadAudio(downloadPath).subscribeOn(Schedulers.io()).observeOn(Schedulers.io()).subscribe(new DefaultObserver<ResponseBody>() {
            @Override
            public void onNext(ResponseBody responseBody) {

                LogcatUtils.d("Download  Audio contentLength长度:  " + responseBody.contentLength());
                boolean b = FileIOUtils.writeFileFromIS(path, responseBody.byteStream());
                LogcatUtils.e("Download Audio isSuccess ! " + b + " - - " + downloadPath);

            }

            @Override
            public void onError(Throwable e) {
                //ToastUtils.showLong("Download Audio onError ! " + " - - " + e.getMessage(),10000);
                LogcatUtils.e("Download Audio onError ! " + " - - " + e.getMessage());
            }

            @Override
            public void onComplete() {
                //ToastUtils.showLong("Download Audio onComplete ! ");
                LogcatUtils.e("Download Audio onComplete " + fileName);

            }
        });

    }


    private void downloadApk(CheckVersionBean versionBean) {
        ToastUtils.showShort("Application is being upgraded", 10000);

        LogcatUtils.e("Download apk 执行下载 app下载地址 " + versionBean.getUrl());
        String fileName = StringUtils.getString("zdhx_AD", ".apk");
        File d = new File(FilePathUtils.getInstance().getCacheStore(), "zdhx");
        FilePathUtils.getInstance().deleteDirFile(d);
        if (!d.exists()) {
            d.mkdirs();
        }
        String path = d.getAbsolutePath().concat("/").concat(fileName);
        LogcatUtils.e(" Download apk 执行下载 apk path " + path);
        CacheUtils.setString(Constants.fileDownApkName, path);

        mApiService.downloadApk(versionBean.getUrl()).subscribeOn(Schedulers.io()).observeOn(Schedulers.io()).subscribe(new DefaultObserver<ResponseBody>() {
            @Override
            public void onNext(ResponseBody responseBody) {

                boolean b = FileIOUtils.writeFileFromIS(path, responseBody.byteStream());
                if (b) {
                    //下载完成后安装Apk
                    installAndRestart();
                } else {
                    //ToastUtils.showLong("Download apk Fail ! " + " - - " + urlPath,10000);
                    LogcatUtils.e("Download apk Fail ! " + " - - " + versionBean.getUrl());
                }
            }

            @Override
            public void onError(Throwable e) {
                //ToastUtils.showLong("Download apk onError ! " + " - - " + e.getMessage(),10000);
                LogcatUtils.e("Download apk onError ! " + " - - " + e.getMessage());
            }

            @Override
            public void onComplete() {
                //ToastUtils.showLong("Download apk onComplete ! ");
                LogcatUtils.e("Download apk onComplete ");
            }
        });

    }


    private long getFileSize(String path) {
        // 获取文件大小
        File file = new File(path);
        return file.length();
    }


    private void startDownload(String url, float fileSize, boolean isOld) {
        experienceProgressBar.setVisibility(View.VISIBLE);
        tvProgressBar.setVisibility(View.VISIBLE);

        String fileName = StringUtils.getString("update", ".zip");
        if (isOld) {
            String sdcardPath = Environment.getExternalStorageDirectory().getAbsolutePath();

            downloadPath = sdcardPath.concat("/").concat(fileName);
        } else {
            File d = new File(FilePathUtils.getInstance().getCacheStore(), "System");
            FilePathUtils.getInstance().deleteDirFile(d);
            if (!d.exists()) {
                d.mkdirs();
            }
            downloadPath = d.getAbsolutePath().concat("/").concat(fileName);
        }
        Disposable disposable = FileDownloader.getInstance().downloadFile(url, downloadPath, fileSize, new FileDownloader.ProgressListener() {
                    @Override
                    public void onProgress(float progress) {
                        experienceProgressBar.setProgress((int) progress);
                        tvProgressBar.setText(LangHelper.regularizePrice(progress) + "%");
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .retry(30) // 下载失败时重试3次
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        if (isOld) {

                            ShellUtils.execCmd("reboot");

                        } else {

                            manager.upgradeSystem(downloadPath);
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        LogcatUtils.e("Download img 执行下载 Img 失败  " + throwable.toString());
                        startDownload(url, fileSize, isOld); // 重新下载
                    }
                });

        compositeDisposable.add(disposable);
    }


    /**
     * 安装并重启
     */

    public void installAndRestart() {
        LogcatUtils.e("Download apk installAndRestart 开始静默安装 isAppRoot:  " + ShellUtils.is_root());
        String apkPath = CacheUtils.getString(Constants.fileDownApkName);
        LogcatUtils.e("Download apk  installAndRestart 开始静默安装 apkPath:  " + apkPath);
        File apkfile = new File(apkPath);
        if (FileUtils.isFileExists(apkfile)) {
            try {
                StringBuilder v1 = new StringBuilder();
                String packageName = AppUtils.getApkInfo(apkfile).getPackageName();
                v1.append("pm install -i " + packageName + " -r --user 0 ");
                v1.append(apkPath);
                LogcatUtils.e("Download apk 静默安装 StringBuilder ::: " + v1.toString());
                Process process = Runtime.getRuntime().exec("su");
                DataOutputStream os = new DataOutputStream(process.getOutputStream());
                os.write(v1.toString().getBytes());
                os.writeBytes("\n");
                os.writeBytes("exit\n");
                os.flush();
                LogcatUtils.e("Download apk   静默安装 执行命令");
                //执行命令
                int a = process.waitFor();
                //0 为正常
                LogcatUtils.e("Download apk   静默安装 执行命令 waitFor返回值: " + a);

            } catch (IOException e) {
                LogcatUtils.e("Download apk   静默安装结果222:" + e.toString());
                e.printStackTrace();
            } catch (InterruptedException e) {
                LogcatUtils.e("Download apk   静默安装结果333:" + e.toString());
                e.printStackTrace();
            }
        } else {
            LogcatUtils.e("Download apk   installAndRestart 安装文件不存在:");
        }
    }


    @Override
    public void onSucceed(JSONObject jsonData, int id, CommonalityModel commonality) throws JSONException {
        JSONObject data = jsonData.optJSONObject("data");
        switch (id) {
            case ApiUrl.get_Wss_Address_Id:
                dealWithDeviceInfo(jsonData.toString());
                break;
            case ApiUrl.get_Advertising_Id:
                stopProgressDialog();
                dealWithAd(jsonData.toString());
                break;
            case ApiUrl.check_version_Id:
                versionBean = GsonUtils.parseJObject(jsonData.toString(), CheckVersionBean.class);

                if (versionBean != null) {
                    LogcatUtils.e("Download   " + JSONFormat.format(versionBean.toString()));

                    if (AppUtils.getAppVersionCode() < versionBean.getVersion()) {
                        downloadApk(versionBean);
                    } else {
                        LogcatUtils.e("Download apk 版本无需更新 ");
                    }
                    LogcatUtils.e("Download img " + resultBA30.successMsg);

                    if (resultBA30.successMsg.equals("BA30-MI-V1.0-MIPI-202309131021")) {
                        if (!StringUtils.isEmpty(versionBean.getSystem_url_old())) {
                            LogcatUtils.e("Download img isOld true ");
                            if (FileUtils.isFileExists("/storage/emulated/0/update.zip")) {
                                String md5File = FileUtils.calculateMD5("/storage/emulated/0/update.zip");
                                LogcatUtils.e("Download img md5File " + md5File.toString());
                                if (!md5File.equals(versionBean.getSystem_url_old_md5())) {
                                    startDownload(versionBean.getSystem_url_old(), versionBean.getFileOLdSize(), true);
                                } else {
                                    mIvQrCode.postDelayed(() -> {
                                        new Thread(() -> {
                                            try {
                                                // 在后台线程中创建 Instrumentation 对象
                                                Instrumentation inst = new Instrumentation();
                                                // 模拟点击事件
                                                inst.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMillis(),
                                                        SystemClock.uptimeMillis(),
                                                        MotionEvent.ACTION_DOWN, 789, 453, 0));
                                                inst.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMillis(),
                                                        SystemClock.uptimeMillis(),
                                                        MotionEvent.ACTION_UP, 789, 453, 0));
                                                LogcatUtils.e("Download img 执行鼠标点击按钮 执行成功");
                                            } catch (Exception e) {
                                                LogcatUtils.e("Download img 执行鼠标点击按钮 执行异常: " + e.getMessage());
                                            }
                                        }).start();
                                    }, 40 * 1000); // 延迟时间设置为0，表示立即执行
                                }
                            } else {
                                startDownload(versionBean.getSystem_url_old(), versionBean.getFileOLdSize(), true);
                            }
                        }

                    } else {
                        if (FileUtils.isFileExists("/storage/emulated/0/update.zip")) {
                            LogcatUtils.e("Download img  升级固件完成 执行删除老版本固件 " + resultBA30.successMsg);
                            ToastUtils.showShort("升级固件完成 执行删除老版本固件 10秒后重启 ", 10000);
                            FileUtils.delete("/storage/emulated/0/update.zip");
                            mIvQrCode.postDelayed(() -> {
                                ShellUtils.execCmd("reboot");
                            }, 10 * 1000); // 延迟时间设置为0，表示立即执行
                        }


                        if (!manager.getFirmwareVersion().equals(versionBean.getSystem_code())
                                && !StringUtils.isEmpty(versionBean.getSystem_url())) {
                            LogcatUtils.e("Download img 系统 版本更新 ");
                            startDownload(versionBean.getSystem_url(), versionBean.getFileSize(), false);
                        } else {
                            LogcatUtils.e("Download img 系统 版本无需更新 ");
                        }
                    }

                }
                break;
            case ApiUrl.screen_rent_Id:
                rentBean = GsonUtils.parseJObject(jsonData.toString(), RentBean.class);
                if (result == 1) {
                    beepManager.startAudio(Constants.rent_success);
                } else {
                    beepManager.startAudio(Constants.rent_fail);
                }

                /*开始设置横竖屏对应的区块划分 并且设置高度*/
                if (rentBean != null) {
                    if (screenOrientation == 1) { //竖屏
                        showResultPopup(result, result == 1 ? rentBean.success_text : rentBean.fail_text, result == 1 ? rentBean.success_content : rentBean.fail_content, result == 1 ? rentBean.success_vertical : rentBean.fail_vertical);
                    } else { //横屏
                        showResultPopup(result, result == 1 ? rentBean.success_text : rentBean.fail_text, result == 1 ? rentBean.success_content : rentBean.fail_content, result == 1 ? rentBean.success_cross : rentBean.fail_cross);
                    }
                }
                break;
            case ApiUrl.screen_return_Id:
                rentBean = GsonUtils.parseJObject(jsonData.toString(), RentBean.class);
                if (result == 1) {
                    beepManager.startAudio(Constants.return_success);
                } else {
                    beepManager.startAudio(Constants.return_fail);
                }
                /*开始设置横竖屏对应的区块划分 并且设置高度*/
                if (rentBean != null) {
                    if (screenOrientation == 1) { //竖屏
                        showResultPopup(result, result == 1 ? rentBean.success_text : rentBean.fail_text, result == 1 ? rentBean.success_content : rentBean.fail_content, result == 1 ? rentBean.success_vertical : rentBean.fail_vertical);
                    } else { //横屏
                        showResultPopup(result, result == 1 ? rentBean.success_text : rentBean.fail_text, result == 1 ? rentBean.success_content : rentBean.fail_content, result == 1 ? rentBean.success_cross : rentBean.fail_cross);
                    }
                }
                break;


        }
    }

    @Override
    public void onFail(JSONObject jsonData, int id, CommonalityModel commonality) {

        ToastUtils.showShort(commonality.getMsg());
        switch (id) {
            case ApiUrl.get_Wss_Address_Id:
                if (commonality.getStatusCode() == 2) {
                    showErrorPopup("提示", commonality.getMsg(), CacheUtils.getString(Constants.mac_address));
                } else {
                    dealWithDeviceInfo(CacheDoubleStaticUtils.getString(Constants.deviceData));
                    imgNetworkError.setVisibility(View.GONE);
                    LogcatUtils.e("getDeviceInfo 加载失败  执行缓存 ");
                }

                break;

            case ApiUrl.get_Advertising_Id:
                stopProgressDialog();
                dealWithAd(CacheDoubleStaticUtils.getString(Constants.adData));
                imgNetworkError.setVisibility(View.GONE);
                LogcatUtils.e("广告数据 加载失败 stopProgressDialog 执行缓存");
                break;

            case ApiUrl.check_version_Id:
                break;


        }
    }

    @Override
    public void onError(int id, Exception e) {
        switch (id) {
            case ApiUrl.get_Wss_Address_Id:

                if (!TextUtils.isEmpty(CacheDoubleStaticUtils.getString(Constants.deviceData))) {
                    dealWithDeviceInfo(CacheDoubleStaticUtils.getString(Constants.deviceData));
                    imgNetworkError.setVisibility(View.GONE);
                    LogcatUtils.e("getDeviceInfo 加载错误  ");
                }
                reLoadDate(0);
                break;

            case ApiUrl.get_Advertising_Id:
                stopProgressDialog();
                reLoadDate(1);
                LogcatUtils.e("广告数据 加载错误 stopProgressDialog 走缓存   执行重新加载 ");
                if (!TextUtils.isEmpty(CacheDoubleStaticUtils.getString(Constants.adData))) {
                    dealWithAd(CacheDoubleStaticUtils.getString(Constants.adData));
                    imgNetworkError.setVisibility(View.GONE);
                }
                break;

            case ApiUrl.check_version_Id:
                reLoadDate(3);
                LogcatUtils.e("版本更新数据 加载错误   url " + ApiUrl.check_version + " 执行重新加载 ");
                break;


        }
    }

    @Override
    public void onBackPressed() {
        moveTaskToBack(true);
       /* moveTaskToBack(false);
        System.exit(0);
        intent = new Intent(Intent.ACTION_MAIN);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addCategory(Intent.CATEGORY_HOME);
        startActivity(intent);
        ManageActivity.closeAllActivity();*/
        // super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (!compositeDisposable.isDisposed()) {
            compositeDisposable.dispose();
        }
    }


}